package com.hassean.we.admin.exteriorController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hassean.we.admin.common.constant.CommonConstant;
import com.hassean.we.admin.common.util.PrepareCall;
import com.hassean.we.admin.common.util.R;
import com.hassean.we.admin.common.util.template.MD5Util;
import com.hassean.we.admin.model.entity.*;
import com.hassean.we.admin.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yajun on 2019/4/9
 * 所有调外部接口的请求
 */
@Api(description = "所有调外部接口的请求")
@RestController
@RequestMapping("/HttpClientController")
public class HttpClientController {
    private static Logger logger = Logger.getLogger(HttpClientController.class);
    @Autowired
    private HttpClientService httpClientService;
    @Autowired
    private TbTerminalLocationService tbTerminalLocationService;
    @Autowired
    private TbTerminalService tbTerminalService;
    @Autowired
    private TbMessageService tbMessageService;
    @Autowired
    private TbCallService tbCallService;
    @Autowired
    private TbSimFlowService tbSimFlowService;
    @Autowired
    private  TbSimChargesService tbSimChargesService;
    @Autowired
    private  TbRescueService tbRescueService;
    @Autowired
    private TbSimInfoService tbSimInfoService;
    @ApiOperation(value = "测试httpClient" ,  notes="测试httpClient")
    @RequestMapping("/getData")
    public Object getHttpClintMath()throws JSONException {
        httpClientService.getData();
        return  null;
    }
    /**
     * 终端（轨迹）信息和状态,每10分钟钟执行一次，开启程序时候启动(正式)
     */

//    @Scheduled(fixedRate = 1000*60*10)//关闭定时器
    public void getLocation(){
        //请求外部数据
        System.out.println("终端（轨迹）信息和状态？,每10分钟执行一次，开启程序时候启动");
        Map<String ,Object> resultMap  = httpClientService.getLocation();
        Integer  result = Integer.parseInt(resultMap.get("result").toString());
        if (result==0||result==1){
            List<List>list = (List)resultMap.get("list");
            if(!list.isEmpty()){
                for (int i = 0; i <list.size() ; i++) {
                    Long terminal_id =null;
                    String Phone = (String)list.get(0).get(0);//获取电话号码
                    /**
                     * map:{result=0, list=[["17406000024","108.957944","34.13625","20181109135233"],["17406001111","120.853778","30.741556","20181102154616"]]}
                     result:{"list":[["17406000024","108.957944","34.13625","20181109135233"],["17406001111","120.853778","30.741556","20181102154616"]],"result":"0"}

                     list.get(0).get(0);17406000024
                     list.get(0).get(1);108.957944
                     list.get(0).get(2);34.13625
                     list.get(0).get(3);20181109135233
                     list.size():2
                     */

                    //map:{result=0, list=[["17406000024","108.957944","34.13625","20181109135233"],["17406001111","120.853778","30.741556","20181102154616"]]}

                    List<Map<String, Object>> resultList = tbTerminalService.selectTerminalIdByPhone(Phone);
                    //获取被叫终端id
                    if(!resultList.isEmpty()){
                        terminal_id = (Long)resultList.get(0).get("terminal_id");

                    }


                    Double  longitude = Double.parseDouble(list.get(0).get(1).toString());

                    Double latitude =  Double.parseDouble(list.get(0).get(2).toString());

                    //存入终端轨迹表
                    String add_time = (String) list.get(0).get(3);//时间格式20181109135233
                    StringBuilder sb = new StringBuilder(add_time);//构造一个StringBuilder对象
                    //右边先插，左边后插
                    sb.insert(add_time.lastIndexOf(""), "'");//在末尾，插入指定的字符串':
                    sb.insert(12, ":");//在指定的位置6，插入指定的字符串:
                    sb.insert(10, ":");//在指定的位置6，插入指定的字符串:
                    sb.insert(8, " ");//在指定的位置6，插入指定的字符串-
                    sb.insert(6, "-");//在指定的位置6，插入指定的字符串-
                    sb.insert(4, "-");//在指定的位置4，插入指定的字符串-
                    sb.insert(0, "'");//在指定的位置4，插入指定的字符串-
                    add_time = sb.toString();

                    //String add_time ="'2019-04-24 15:55:00'";

                    PrepareCall prepareCall = new PrepareCall();
                    Connection conn = prepareCall.getConnection();  //创建数据库连接
                    try {
                        //调用终端轨迹存储过程
                        CallableStatement cs = conn.prepareCall("{call sp_insert_trajectory(?,?,?,?)}");
                        //mysql数据库代码
                        /**
                         * 动态插入
                         *drop PROCEDURE  sp_insert_trajectory;
                         DELIMITER//
                         CREATE PROCEDURE sp_insert_trajectory(in terminal_id int(20),in longitude DOUBLE(10,6),in latitude DOUBLE(10,6),in add_time VARCHAR(30))
                         BEGIN
                         SET @dateStr = DATE_FORMAT(NOW(), '%Y%m');
                         SET @sqlStr:=CONCAT("insert into tb_terminal_trajectory_",@dateStr," (terminal_id,longitude,latitude,add_time)
                         VALUES(",terminal_id,",",longitude,",",latitude,",",add_time,")");
                         PREPARE stmt from @sqlStr;
                         EXECUTE stmt;
                         DEALLOCATE PREPARE stmt;
                         END
                         //

                         SET @longitude =112.345;
                         SET @latitude = 23.44;
                         set @add_time ="'2019-04-24 15:55:00'";
                         set @terminal_id =1;
                         call sp_insert_trajectory(@terminal_id,@longitude,@latitude,@add_time);
                         */

                        cs.setLong(1, terminal_id);
                        cs.setDouble(2,longitude);
                        cs.setDouble(3,latitude);
                        cs.setString(4,add_time);
                        ResultSet rs = cs.executeQuery(); //执行操作，并获取结果集

                        conn.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //存入终端位置表
                    TbTerminalLocation tbTerminalLocation = tbTerminalLocationService.selectById(terminal_id);
                    if(tbTerminalLocation!=null){
                        tbTerminalLocation.setTerminalId(terminal_id);
                        tbTerminalLocation.setLatitude(latitude);
                        tbTerminalLocation.setLongitude(longitude);
                        tbTerminalLocation.setAddTime(new Date());
                        tbTerminalLocationService.insert(tbTerminalLocation);
                    }

                }
            }

        }

    }


    //测试位置信息接口(测试)
    @RequestMapping("/testGetlocation2")
    public void getlocation2(){
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/getLocation");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());
        //开始时间
        String beginTime  ="20190110120059";
        //结束时间
        String endTime = "20190111120059";;
        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次


        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();
        // strList.add("17406000024");
        // strList.add("17406001111");
        strList.add("");
        jsonParam.put("beginTime",beginTime);
        jsonParam.put("endTime",endTime);
        jsonParam.put("strList",strList);//如果strList为空，取全部
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        // System.out.println(jsonParam.toString());

        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> map = JSON.parseObject(result, Map.class);
            System.out.println("map:"+map);
            /**
             * 返回值
             * map:{result=0, list=[["17406000024","108.957944","34.13625","20181109135233"],
             *                     ["17406001111","120.853778","30.741556","20181102154616"]]}
             */
            System.out.println(map.get("result"));
            System.out.println("result:"+result);
            Integer  state = Integer.parseInt(map.get("result").toString());
            List<List>list = (List)map.get("list");
            Long  terminal_id = null;
            List<Map<String, Object>> resultList = tbTerminalService.selectTerminalIdByPhone( (String) list.get(0).get(0));
            //获取被叫终端id
            if(!resultList.isEmpty()){
                terminal_id = (Long)resultList.get(0).get("terminal_id");

            }
            System.out.println("list.get(0).get(0);"+ list.get(0).get(0));

            Double  longitude =null;
            longitude = Double.parseDouble(list.get(0).get(1).toString());

            Double latitude =  Double.parseDouble(list.get(0).get(2).toString());


            //存入终端位置表
            TbTerminalLocation tbTerminalLocation = tbTerminalLocationService.selectById(terminal_id);
            if(tbTerminalLocation!=null){
                tbTerminalLocation.setTerminalId(terminal_id);
                tbTerminalLocation.setLatitude(latitude);
                tbTerminalLocation.setLongitude(longitude);
                tbTerminalLocation.setAddTime(new Date());
                tbTerminalLocationService.insert(tbTerminalLocation);
            }

            System.out.println("list.get(0).get(0);"+ list.get(0).get(0));
            System.out.println("list.get(0).get(1);"+ list.get(0).get(1));
            System.out.println("list.get(0).get(2);"+ list.get(0).get(2));
            System.out.println("list.get(0).get(3);"+ list.get(0).get(3));//20181109135233  时间需要格式化
            //还没写完

            System.out.println("list.size():"+list.size());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * SIM卡的流量开关(后台人工操作，正式)
     */
    @ApiOperation(value = "SIM卡的流量开关" ,  notes="SIM卡的流量开关")
    @RequestMapping("/simFlowOffAndON")
    public R<Boolean> simFlowOffAndON(@RequestParam Long simInfoId,@RequestParam Long status,@RequestParam String phoneNumber){
        Boolean flag = true;
        flag =   httpClientService.simFlowOffAndON(simInfoId,status,phoneNumber);
        return new R<>(flag);
    }

    /**
     * 测试SIM卡的流量开关（测试）
     */
    @RequestMapping("/getSimFlowOffAndOn2")
    public void getSimFlowOffAndON(){
        Map<String, Object> map = new HashMap<>();

        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url + "/tisp/simFlowOffAndOn");

        String spName = CommonConstant.spName;//还没有这个参数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String requestTime = sdf.format(new Date());
        String spPwd = CommonConstant.spPwd;//还没有这个参数
        String token = spName + requestTime + spPwd;
        //token是否需要MD5加密
        MD5Util mD5Util = new MD5Util();
        token = mD5Util.getMD5String(token);//MD5加密一次


        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<List>phoneNumber = new ArrayList<>();
        List<Object>list = new ArrayList<>();
        list.add("18822834812");
        list.add(0);//没有定义
        phoneNumber.add(list);
        jsonParam.put("phoneNumber",phoneNumber);
        StringEntity json = new StringEntity(jsonParam.toString(), "utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        System.out.println(jsonParam.toString());

        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            map = JSON.parseObject(result, Map.class);
            System.out.println("map:" + map);
            Integer  state = Integer.parseInt(map.get("result").toString());
            //map:{list=[["18822834812","0"]]}
            System.out.println(map.get("result"));
            System.out.println("result:" + result);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 短信记录
     */
//    @Scheduled(fixedRate = 1000*60*10)//关闭定时器
    public void tbMessageRrcord()throws ParseException {
        Map<String, Object> resultMap = httpClientService.tbMessageRrcord();
        Integer result = Integer.parseInt(resultMap.get("result").toString());

        if (result == 0 || result == 1) {
            List<List> list = (List) resultMap.get("list");
            if (!list.isEmpty()) {
                for (int i = 0; i < list.size(); i++) {
                    Long callingTerminalId = null;
                    String callingPhone = (String) list.get(0).get(0);//主叫电话号码
                    List<Map<String, Object>> callingList = tbTerminalService.selectTerminalIdByPhone(callingPhone);
                    //获取主叫终端id
                    if (!callingList.isEmpty()) {
                        callingTerminalId = (Long) callingList.get(0).get("terminal_id");
                    }
                    Long passivityTerminalId = null;
                    String passivityPhone = (String) list.get(0).get(1);//被叫电话号码
                    List<Map<String, Object>> passivityList = tbTerminalService.selectTerminalIdByPhone(passivityPhone);
                    //获取被叫终端id
                    if (!passivityList.isEmpty()) {
                        passivityTerminalId = (Long) passivityList.get(0).get("terminal_id");
                    }


                    TbMessage tbMessage = new TbMessage();
                    tbMessage.setCallingTerminalId(callingTerminalId);
                    tbMessage.setPassivityTerminalId(passivityTerminalId);


                    String addTimes = (String) list.get(0).get(2);
                    StringBuilder sb = new StringBuilder(addTimes);//构造一个StringBuilder对象
                    //右边先插，左边后插

                    sb.insert(12, ":");//在指定的位置6，插入指定的字符串:
                    sb.insert(10, ":");//在指定的位置6，插入指定的字符串:
                    sb.insert(8, " ");//在指定的位置6，插入指定的字符串-
                    sb.insert(6, "-");//在指定的位置6，插入指定的字符串-
                    sb.insert(4, "-");//在指定的位置4，插入指定的字符串-

                    addTimes = sb.toString();

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date add_time = sdf.parse(addTimes);
                    tbMessage.setAddTime(add_time);

                    tbMessage.setState(3);//1已发送、2未发送3未处理，4已处理

                    tbMessageService.insert(tbMessage);
                }
            }
        }
    }

    /**
     * 救援信息申请入口（正式）
     * @throws ParseException
     */
    @RequestMapping("/applyRescueMessage")
    public void applyRescueMessage()throws ParseException {
        Map<String, Object> resultMap = httpClientService.applyRescueMessage();
        Integer result = Integer.parseInt(resultMap.get("result").toString());
        if (result ==0) {
            System.out.println("申请成功");
        }
    }

    /**
     * 测试救援信息申请入口(测试)
     * @throws ParseException
     */
    @RequestMapping("/testApplyRescueMessage2")
    public void testApplyRescueMessage()throws ParseException {
        Map<String, Object> resultMap = httpClientService.applyRescueMessage();
        Integer result = Integer.parseInt(resultMap.get("result").toString());
        if (result ==0) {
            System.out.println("申请成功");
        }
    }
    /**
     * 通话记录
     */
//    @Scheduled(fixedRate = 1000*60*10)//关闭定时器
    public void tbCallRrcord()throws ParseException {
        Map<String ,Object> resultMap =  httpClientService.tbCallRrcord();
        Integer  result = Integer.parseInt(resultMap.get("result").toString());
        if (result==0||result==1){
            List<List>list = (List)resultMap.get("list");
            if(!list.isEmpty()){
                for (int i = 0; i <list.size() ; i++) {
                    Long callingTerminalId =null;
                    String callingPhone = (String)list.get(0).get(0);//主叫电话号码
                    List<Map<String, Object>>  callingList = tbTerminalService.selectTerminalIdByPhone(callingPhone);
                    //获取主叫终端id
                    if(!callingList.isEmpty()){
                        callingTerminalId = (Long)callingList.get(0).get("terminal_id");
                    }
                    Long passivityTerminalId =null;
                    String passivityPhone = (String)list.get(0).get(1);//被叫电话号码
                    List<Map<String, Object>> passivityList = tbTerminalService.selectTerminalIdByPhone(passivityPhone);
                    //获取被叫终端id
                    if(!passivityList.isEmpty()){
                        passivityTerminalId = (Long)passivityList.get(0).get("terminal_id");
                    }

                    TbCall tbCall = new TbCall();
                    tbCall.setCallingTerminalId(callingTerminalId);
                    tbCall.setPassivityTerminalId(passivityTerminalId);
                    String addTimes = (String)list.get(0).get(2);
                    StringBuilder sb = new StringBuilder(addTimes);//构造一个StringBuilder对象
                    //右边先插，左边后插

                    sb.insert(12, ":");//在指定的位置6，插入指定的字符串:
                    sb.insert(10, ":");//在指定的位置6，插入指定的字符串:
                    sb.insert(8, " ");//在指定的位置6，插入指定的字符串-
                    sb.insert(6, "-");//在指定的位置6，插入指定的字符串-
                    sb.insert(4, "-");//在指定的位置4，插入指定的字符串-

                    addTimes = sb.toString();

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date add_time = sdf.parse(addTimes);

                    tbCall.setAddTime(add_time);
                    String duration = (String)list.get(0).get(3);
                    tbCall.setDuration(duration);
                    Integer  state = Integer.valueOf((list.get(0).get(4)).toString());

                    tbCall.setState(state);//1接通2未接3拒接4未处理5未处理
                    tbCallService.insert(tbCall);
                }
                }
            }
    }

    /**
     * 卡流量记录（正式）
     */
//    @Scheduled(fixedRate = 1000*60*10)//关闭定时器
    public void tbSimFlowRrcord()throws ParseException {
        httpClientService.tbSimFlowRrcord();


    }
    /**
     * 卡资费记录（正式）
     */
//    @Scheduled(fixedRate = 1000*60*10)//关闭定时器
    public void tbSimChargesRrcord()throws ParseException {
        List<Map<String, Object>>list =  httpClientService.tbSimChargesRrcord();
        if (!list.isEmpty()) {
            for (Map<String, Object> map : list) {
                Long sim_info_id =null;
                String message_charges = null;
                String flow_charges = null;
                String call_charges = null;
                String rent = null;
                String total_charges = null;
                String surplus_charges = null;
                String Phone =  (String)map.get("Phone");//电话号码

                List<Map<String, Object>>  mapListist = tbTerminalService.selectTerminalIdByPhone(Phone);
                //获取主叫终端id
                if(!mapListist.isEmpty()){
                    EntityWrapper entity = new EntityWrapper<>();
                    entity.eq("sim_number",Phone);
                    List<TbSimFlow>selectList =    tbSimFlowService.selectList(entity);
                    if (!selectList.isEmpty()){
                        sim_info_id =   selectList.get(0).getSimInfoId();
                    }
                    message_charges = (String)mapListist.get(0).get("message_charges");
                    call_charges = (String)mapListist.get(0).get("call_charges");
                    flow_charges = (String)mapListist.get(0).get("flow_charges");
                    rent = (String)mapListist.get(0).get("rent");
                    total_charges = (String)mapListist.get(0).get("total_charges");
                    surplus_charges = (String)mapListist.get(0).get("surplus_charges");
                }

                TbSimCharges tbSimCharges = new  TbSimCharges();
                tbSimCharges.setSimInfoId(sim_info_id);
                tbSimCharges.setCallCharges(call_charges);
                tbSimCharges.setFlowCharges(flow_charges);
                tbSimCharges.setMessageCharges(message_charges);
                tbSimCharges.setRent(rent);
                tbSimCharges.setTotalCharges(total_charges);
                tbSimCharges.setSurplusCharges(surplus_charges);
                String addTimes = (String)map.get("addTimes");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date addTime = sdf.parse(addTimes);
                tbSimCharges.setAddTime(addTime);
                tbSimChargesService.insert(tbSimCharges);
            }
        }
    }
    //测试资费接口（测试）
    @RequestMapping("/getCharge2")
    public void getCharge(){
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/getCharge");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());
        //开始时间
        String beginTime  ="20180631000001";
        //结束时间
        String endTime = "20181228000001";;
        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次


        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();
        strList.add("18955501400");
        strList.add("18955501401");
        //获取所有最新的资费信息
        jsonParam.put("strList",strList);//如果strList为空，取全部
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        System.out.println(jsonParam.toString());

        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> map = JSON.parseObject(result, Map.class);
            System.out.println("map:"+map);
            /**
             * 返回值
             * map:map:{result=1, list=[["18955501400","17406000014","2018-7-31.11.15. 9. 0","19","0"],["18955501400","17406000014","2018-7-31.11.15. 9. 0","19","0"],
             ["18955501400","17406000014","2018-7-31.11.15. 9. 0","19","0"],
             ["18955501400","17406000014","2018-7-31.11.15. 9. 0","19","0"]]}
             */
            System.out.println(map.get("result"));
            System.out.println("result:"+result);
            Integer  state = Integer.parseInt(map.get("result").toString());
            //  List<List>list = (List)map.get("list");

//            list.get(0).get(0);//List里面套List
//            System.out.println("list.get(0).get(0);"+ list.get(0).get(0));
//            System.out.println("list.get(0).get(1);"+ list.get(0).get(1));
//            System.out.println("list.get(0).get(2);"+ list.get(0).get(2));
//            System.out.println("list.get(0).get(3);"+ list.get(0).get(3));//20181109135233  时间需要格式化
            //还没写完

            // System.out.println("list.size():"+list.size());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    //测试发送短信接口（测试）
    @RequestMapping("/pointToPointSendMessage2")
    public void pointToPointSendMessage(){
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/getSendMessage");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());

        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次
        String recNumber ="18822834812";
        String content = "我是短信内容123";
        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();
        strList.add(recNumber);

        jsonParam.put("strList",strList);
        jsonParam.put("message",content);
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        // System.out.println(jsonParam.toString());

        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> map = JSON.parseObject(result, Map.class);
            System.out.println("map:"+map);
            //map:
            System.out.println(map.get("result"));
            System.out.println("result:"+result);
            Integer  state = Integer.parseInt(map.get("result").toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //测试短信记录接口（测试）
    @RequestMapping("/getSMSRecord2")
    public void getSMSRecord(){
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/getSMSRecord");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());
        //开始时间
        String beginTime  ="20190409000059";
        //结束时间
        String endTime = "20190410000059";
        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次


        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();
        strList.add("");

        jsonParam.put("beginTime",beginTime);
        jsonParam.put("endTime",endTime);
        jsonParam.put("strList",strList);//如果strList为空，取全部
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        System.out.println(jsonParam.toString());

        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> map = JSON.parseObject(result, Map.class);
            System.out.println("map:"+map);
            //map:{result=0, list=[["17406000024","108.957944","34.13625","20181109135233"],["17406001111","120.853778","30.741556","20181102154616"]]}
            System.out.println(map.get("result"));
            System.out.println("result:"+result);
            Integer  state = Integer.parseInt(map.get("result").toString());
            List<List> list = (List) map.get("list");

            Long callingTerminalId = null;
            String callingPhone = (String) list.get(0).get(0);//主叫电话号码
            List<Map<String, Object>> callingList = tbTerminalService.selectTerminalIdByPhone(callingPhone);
            //获取主叫终端id
            if (!callingList.isEmpty()) {
                callingTerminalId = (Long) callingList.get(0).get("terminal_id");
            }
            Long passivityTerminalId = null;
            String passivityPhone = (String) list.get(0).get(1);//被叫电话号码
            List<Map<String, Object>> passivityList = tbTerminalService.selectTerminalIdByPhone(passivityPhone);
            //获取被叫终端id
            if (!passivityList.isEmpty()) {
                passivityTerminalId = (Long) passivityList.get(0).get("terminal_id");
            }


            TbMessage tbMessage = new TbMessage();
            tbMessage.setCallingTerminalId(callingTerminalId);
            tbMessage.setPassivityTerminalId(passivityTerminalId);


//            String addTimes = (String) list.get(0).get(2);
//            StringBuilder sb = new StringBuilder(addTimes);//构造一个StringBuilder对象
//            //右边先插，左边后插
//
//            sb.insert(12, ":");//在指定的位置6，插入指定的字符串:
//            sb.insert(10, ":");//在指定的位置6，插入指定的字符串:
//            sb.insert(8, " ");//在指定的位置6，插入指定的字符串-
//            sb.insert(6, "-");//在指定的位置6，插入指定的字符串-
//            sb.insert(4, "-");//在指定的位置4，插入指定的字符串-
//
//            addTimes = sb.toString();
//
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date add_time = sdf.parse(addTimes);
//            tbMessage.setAddTime(add_time);

            tbMessage.setState(3);//1已发送、2未发送3未处理，4已处理

            tbMessageService.insert(tbMessage);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //测试通话记录接口（测试）
    @RequestMapping("/getVoiceRecord2")
    public void getVoiceRecord(){
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/getVoiceRecord");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());
        //开始时间
        String beginTime  ="20180730000001";
        //结束时间
        String endTime = "20180731000001";
        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次


        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();
        strList.add("");

        jsonParam.put("beginTime",beginTime);
        jsonParam.put("endTime",endTime);
        jsonParam.put("strList",strList);//如果strList为空，取全部
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        System.out.println(jsonParam.toString());

        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> resultMap = JSON.parseObject(result, Map.class);
            System.out.println("resultMap:"+resultMap);


            List<List>list = (List)resultMap.get("list");
            Long callingTerminalId =null;
            String callingPhone = (String)list.get(0).get(0);//主叫电话号码
            List<Map<String, Object>>  callingList = tbTerminalService.selectTerminalIdByPhone(callingPhone);
            //获取主叫终端id
            if(!callingList.isEmpty()){
                callingTerminalId = (Long)callingList.get(0).get("terminal_id");
            }
            Long passivityTerminalId =null;
            String passivityPhone = (String)list.get(0).get(1);//被叫电话号码
            List<Map<String, Object>> passivityList = tbTerminalService.selectTerminalIdByPhone(passivityPhone);
            //获取被叫终端id
            if(!passivityList.isEmpty()){
                passivityTerminalId = (Long)passivityList.get(0).get("terminal_id");
            }

            TbCall tbCall = new TbCall();
            tbCall.setCallingTerminalId(callingTerminalId);
            tbCall.setPassivityTerminalId(passivityTerminalId);
            String addTimes = (String)list.get(0).get(2);
//            StringBuilder sb = new StringBuilder(addTimes);//构造一个StringBuilder对象
//            //右边先插，左边后插
//
//            sb.insert(12, ":");//在指定的位置6，插入指定的字符串:
//            sb.insert(10, ":");//在指定的位置6，插入指定的字符串:
//            sb.insert(8, " ");//在指定的位置6，插入指定的字符串-
//            sb.insert(6, "-");//在指定的位置6，插入指定的字符串-
//            sb.insert(4, "-");//在指定的位置4，插入指定的字符串-

//            addTimes = sb.toString();

            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
//                Date add_time = sd.parse(addTimes);
                //tbCall.setAddTime(add_time);
            }catch (Exception e) {
                e.printStackTrace();
            }



            String duration = (String)list.get(0).get(3);
            tbCall.setDuration(duration);
            Integer  state = Integer.valueOf((list.get(0).get(4)).toString());

            tbCall.setState(state);//1接通2未接3拒接4未处理5未处理
            tbCallService.insert(tbCall);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //测试流量记录接口（测试）
    @RequestMapping("/simFlowRecord2")
    public void simFlowRecord(){
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/simFlowRecord");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());
        //开始时间
        String beginTime  ="20180631000001";
        //结束时间
        String endTime = "20181228000001";;
        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次


        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();
        strList.add("18955501400");

        jsonParam.put("beginTime",beginTime);
        jsonParam.put("endTime",beginTime);
        jsonParam.put("strList",strList);//如果strList为空，取全部
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        System.out.println(jsonParam.toString());

        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> map = JSON.parseObject(result, Map.class);
            System.out.println("map:"+map);
            /**
             * 返回值
             * map:{result=0, list=[["18955501400","30M","10M","40M"]]}
             */
            System.out.println(map.get("result"));
            System.out.println("result:"+result);
            Integer  state = Integer.parseInt(map.get("result").toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //测试json
    @RequestMapping("/testJson")
    public String testJson(){
        //json方式
        JSONObject jsonParam = new JSONObject();
        String spName = "yk";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());
        System.out.println("requestTime:"+requestTime);
        String spPwd ="111111";
        String str = spName+requestTime+spPwd;
        System.out.println("str:"+str);
        //token是否需要MD5加密
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次
        System.out.println("token:"+token);
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);

        List<String>strList = new ArrayList<>();
        strList.add("17406000024");
        strList.add("17400312289");
        jsonParam.put("strList",strList);
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        System.out.println(jsonParam.toString());

        return jsonParam.toString();
    }
    //测试获取最大时间
    @RequestMapping("/getMaxAddTime")
    public void getMaxAddTime(){
        List<Map<String, Object>> list =  tbCallService.getMaxAddTime();

        Date addTime = null;
        if(!list.isEmpty()){
            addTime = (Date) list.get(0).get("add_time");

        }else{
            addTime =new Date();

        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Long endTimes =  addTime .getTime() + 60*1000*9 ;//9分钟
        Date date = new Date();
        date.setTime(endTimes);
        String  endTime =  sdf.format(date);

        System.out.println("endTime:"+endTime);
        System.out.println("list.get(0).get(\"add_time\"):"+list.get(0).get("add_time"));
        System.out.println("endTimes:"+endTimes);
    }


    //格式化字符串时间

    public  String date(){
        String add_time = "20181109135233";
        //String add_time ="'2019-04-24 15:55:00'";
        StringBuilder sb = new StringBuilder(add_time);//构造一个StringBuilder对象
        //右边先插，左边后插
        sb.insert(add_time.lastIndexOf(""), "'");//在末尾，插入指定的字符串':
        sb.insert(12, ":");//在指定的位置6，插入指定的字符串:
        sb.insert(10, ":");//在指定的位置6，插入指定的字符串:
        sb.insert(8, " ");//在指定的位置6，插入指定的字符串-
        sb.insert(6, "-");//在指定的位置6，插入指定的字符串-
        sb.insert(4, "-");//在指定的位置4，插入指定的字符串-
        sb.insert(0, "'");//在指定的位置4，插入指定的字符串-
        add_time = sb.toString();
        System.out.println(add_time);
        return add_time;
    }
    /**
     * 实名制查询接口（正式）
     */
    @RequestMapping("/getRegistration")
    public Map<String,Object> getRegistration(){
        List<Map<String,Object>>list = new ArrayList<>();
        Map<String ,Object> resultMap =new HashMap<>();
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/getRegistration");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());

        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次


        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();
        strList.add("18955501400");

        jsonParam.put("strList",strList);//如果strList为空，取全部
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");

        System.out.println(jsonParam.toString());

        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> map = JSON.parseObject(result, Map.class);

            Integer  state = Integer.parseInt(map.get("result").toString());
             if(state==0||state==1){
                 resultMap.put("code",0);
                 List<List> resultList = (List) map.get("list");
                 for (int i = 0; i <resultList.size() ; i++) {
                 String phone = resultList.get(0).get(0).toString();
                     resultMap.put("phone",phone);

                 String departmentName = resultList.get(0).get(1).toString();
                     resultMap.put("departmentName",departmentName);
                 String simOwnerName = resultList.get(0).get(2).toString();
                     resultMap.put("simOwnerName",simOwnerName);
                 }

             }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
    //查询实名认证(测试)
    @RequestMapping("/getRegistration2")
    public Map<String,Object> getRegistration(@RequestParam String phone){
        List<Map<String,Object>>list = new ArrayList<>();
        Map<String ,Object> resultMap =new HashMap<>();
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/getRegistration");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());

        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次


        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();
        strList.add(phone);
        jsonParam.put("strList",strList);//如果strList为空，取全部
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");


        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> map = JSON.parseObject(result, Map.class);
            System.out.println("map:"+map);
            //map:{result=0, list=[["17406000024",null,"中国电信卫星分公司"]]}
            Integer  state = Integer.parseInt(map.get("result").toString());
            if(state==0){
                List<List>resultList = (List)resultMap.get("list");
                if(!resultList.isEmpty()){
                    resultMap.put("phone", list.get(0).get(0));//phone
                    resultMap.put("phone", list.get(0).get(1));//name
                    resultMap.put("phone", list.get(0).get(2));//单位

                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }



    /**
     * <p>
     *  批量更新全部实名认证
     * 批量修改实名认证（最新的认证人）
     * </p>
     *
     */

    @RequestMapping("/updateBatch/registration")
    public R<Boolean> updateBatchRegistration(){
        List<Map<String,Object>>list = new ArrayList<>();
        Map<String ,Object> resultMap =new HashMap<>();
        HttpClient client = HttpClientBuilder.create().build();
        //ip和端口不知道
        HttpPost post = new HttpPost(CommonConstant.url+"/tisp/getRegistration");

        String spName = CommonConstant.spName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String requestTime = sdf.format(new Date());

        String spPwd =CommonConstant.spPwd;
        String str = spName+requestTime+spPwd;
        MD5Util mD5Util = new MD5Util();
        String   token =   mD5Util.getMD5String(str);//MD5加密一次

        Boolean flag = true;
        //把参数转换为json格式
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("spName", spName);
        jsonParam.put("requestTime", requestTime);
        jsonParam.put("token", token);
        List<String>strList = new ArrayList<>();

        List<TbSimInfo>  tbSimInfoList =  getAllTbSimInfo();
        for (int i = 0; i <tbSimInfoList.size() ; i++) {
            strList.add(tbSimInfoList.get(i).getSimNumber());
        }

        jsonParam.put("strList",strList);//如果strList为空，取全部
        StringEntity json = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
        json.setContentEncoding("UTF-8");
        json.setContentType("application/json");


        //添加参数
        try {
            post.setEntity(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();

            String result = EntityUtils.toString(entity, "utf-8");
            Map<String ,Object> map = JSON.parseObject(result, Map.class);
            System.out.println("map:"+map);
            //map:{result=0, list=[["17406000024",null,"中国电信卫星分公司"]]}
            Integer  state = Integer.parseInt(map.get("result").toString());
            Integer total =1000;//每1000次批量操作一次
            if(state==0){
                List<List>resultList = (List)resultMap.get("list");
                List<TbSimInfo> entityList  = new ArrayList<>();
                if(!resultList.isEmpty()){
                    for (int i = 0; i <resultList.size() ; i++) {
                        String sim_number =  resultList.get(i).get(0).toString();//phone
                        EntityWrapper entityWrapper =  new EntityWrapper<>();
                        entityWrapper.eq("sim_number",sim_number);
                        TbSimInfo tbSimInfo = tbSimInfoService.selectOne(entityWrapper);

                        String ownerName =  resultList.get(i).get(1).toString();//认证人
                        tbSimInfo.setOwnerName(ownerName);

                        tbSimInfo.setUpdateTime(new Date());
                        entityList.add(tbSimInfo);

                        //如果总条数小于1000
                        if(resultList.size()<total&&entityList.size()==resultList.size()){
                            flag=   updateBatch(entityList,resultList.size());
                        }else{
                            //如果总条数等于和大于1000
                            //每次1000条操作一次
                            Integer y = i%(total-1);//检查倍数
                            if(i!=0&&y == 0){
                                flag=   updateBatch(entityList,total);
                                entityList = null;
                                entityList = new ArrayList<>();
                            }else{
                                if(resultList.size()-i<total-1){
                                    flag=   updateBatch(entityList,resultList.size()-i);
                                }
                            }

                        }

                    }



                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new R<>(flag);
    }



    //批量执行
    public Boolean   updateBatch(List<TbSimInfo> entityList, int batchSize){

        Boolean flag = true;
        flag =  tbSimInfoService.updateBatchById(entityList, batchSize);
        return flag;
    }

   //获取所有电话卡信息
    public  List<TbSimInfo>  getAllTbSimInfo(){

      List<TbSimInfo>  tbSimInfoList =   tbSimInfoService.selectList(new EntityWrapper<>());


      return  tbSimInfoList;

    }


    //批量修改认证人(测试)
    @RequestMapping("/testUpdateBatch")
    public Boolean   testUpdateBatch(){
        Boolean flag = true;
        EntityWrapper entityWrapper =  new EntityWrapper<>();
        entityWrapper.eq("del_flag","2");
        List<TbSimInfo>  tbSimInfoList =   tbSimInfoService.selectList(entityWrapper);
        TbSimInfo tbSimInfo = null;
        List<TbSimInfo> entityList2 = new ArrayList<>();
        Integer total =3;
        for (int i = 0; i < tbSimInfoList.size(); i++) {
            tbSimInfo = tbSimInfoList.get(i);
            tbSimInfo.setOwnerName("可口可乐2");
            tbSimInfo.setUpdateTime(new Date());
            entityList2.add(tbSimInfo);

            //如果总条数小于1000
            if(tbSimInfoList.size()<total&&entityList2.size()==tbSimInfoList.size()){
                flag =  tbSimInfoService.updateBatchById(entityList2, tbSimInfoList.size());
            }else{
                //如果总条数等于和大于3
                //每次3条操作一次
                Integer y = i%(total-1);//检查倍数
                if(i!=0&&y == 0){
                        flag =  tbSimInfoService.updateBatchById(entityList2, total);
                        entityList2 = null;
                        entityList2 = new ArrayList<>();
                }else{
                    if(tbSimInfoList.size()-i<total-1){

                        flag =  tbSimInfoService.updateBatchById(entityList2, tbSimInfoList.size()-i);
                    }
                }

            }

        }

        return flag;
    }


    //工信部回调应急部接口,救援任务（正式）
    @RequestMapping("/callback/sendRescueMessage")
    public String sendRescueMessage(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("request:"+request);
        try{
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
            StringBuilder reqPara = new StringBuilder();
            String line = null;
            while ((line = in.readLine()) != null) {
                reqPara.append(line);
            }
            Map<String, Object> map  = JSON.parseObject(reqPara.toString(), Map.class);
            System.out.println("reqPara:"+reqPara.toString());
            System.out.println("map:"+map);
            //map:{terminalNumber=17406000024, latitude=170.5, message=被困灾区，等待救援, sendTime=20190523111059, longitude=116.8}
            //reqPara.toString():{"sendTime":"20190523111059","terminalNumber":"17406000024","longitude":"116.8","latitude":"170.5","message":"被困灾区，等待救援"}
             String  terminalNumber = map.get("terminalNumber").toString();
             Double  latitude = Double.parseDouble( map.get("latitude").toString());
             Double  longitude = Double.parseDouble( map.get("longitude").toString());
             String  message = map.get("message").toString();
             String  addTimes = map.get("sendTime").toString();
            StringBuilder sb = new StringBuilder(addTimes);//构造一个StringBuilder对象
            //右边先插，左边后插

            sb.insert(12, ":");//在指定的位置6，插入指定的字符串:
            sb.insert(10, ":");//在指定的位置6，插入指定的字符串:
            sb.insert(8, " ");//在指定的位置6，插入指定的字符串-
            sb.insert(6, "-");//在指定的位置6，插入指定的字符串-
            sb.insert(4, "-");//在指定的位置4，插入指定的字符串-

            addTimes = sb.toString();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date add_time = sdf.parse(addTimes);
            TbRescue tbRescue = new TbRescue();
            tbRescue.setAddTime(add_time);
            tbRescue.setSeekHelpPhoneNumber(terminalNumber);
            tbRescue.setLatitude(latitude);
            tbRescue.setLongitude(longitude);
            tbRescue.setContent(message);
            EntityWrapper entity = new EntityWrapper<>();
            entity.eq("terminalNumber",terminalNumber);
            TbTerminal  tbTerminal =    tbTerminalService.selectOne(entity);
            tbRescue.setRescueTeamId(tbTerminal.getRescueTeamId());
            tbRescueService.insert(tbRescue);

            in.close();
        }catch (Exception e ){
            e.printStackTrace();
        }


        return "回调成功";
    }

    //测试工信部回调应急部接口（测试）
    @RequestMapping("/callback/sendRescueMessage2")
    public String sendRescueMessage2(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("request:"+request);
        try{
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
            StringBuilder reqPara = new StringBuilder();
            String line = null;
            while ((line = in.readLine()) != null) {
                reqPara.append(line);
            }
            Map<String, Object> map  = JSON.parseObject(reqPara.toString(), Map.class);
            System.out.println("reqPara:"+reqPara.toString());
            System.out.println("map:"+map);
            //map:{terminalNumber=17406000024, latitude=170.5, message=被困灾区，等待救援, sendTime=20190523111059, longitude=116.8}
            //reqPara.toString():{"sendTime":"20190523111059","terminalNumber":"17406000024","longitude":"116.8","latitude":"170.5","message":"被困灾区，等待救援"}
            in.close();
        }catch (Exception e ){
            e.printStackTrace();
        }


        return "回调成功";
    }
}
